package com.qqtop10.manager.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.aipg.rtreq.Trans;
import com.allinpay.XmlTools;
import com.qqtop10.manager.dao.WithdrawalMapper;
import com.qqtop10.manager.model.PagingArgs;
import com.qqtop10.manager.model.Points;
import com.qqtop10.manager.model.Withdrawal;
import com.qqtop10.manager.service.PointsService;
import com.qqtop10.manager.service.TranxService;
import com.qqtop10.manager.service.WithdrawalService;

@Service("withdrawalService")
public class WithdrawalServiceImpl extends BaseService implements WithdrawalService {
	@Autowired
	private WithdrawalMapper withdrawalMapper;

	@Autowired
	@Qualifier("tranxService")
	private TranxService tranxService;

	@Override
	public List<Withdrawal> all(Withdrawal input, PagingArgs pagingArgs) {
		return withdrawalMapper.all(asMap(input, pagingArgs));
	}

	@Override
	public int count(Withdrawal input) {
		return withdrawalMapper.count(input);
	}
	private Logger logger = LoggerFactory.getLogger(WithdrawalServiceImpl.class);

	@Autowired
	private PointsService pointsService;
	
	
	
	@Override
	public boolean updateById(Withdrawal input) {
		
		
		if (input.getStatus() == 1 && input.getMoney() > 0) {
			
			int reuslt=updataUserMoney(input);
			if(reuslt==0){
				return false;
			}
			int r=withdrawalMapper.updateById(input);
			return r != 0;
		}else{
			int r=withdrawalMapper.updateById(input);
			
			return r != 0;
		}
	
	}

	@Transactional
	@Override
	public int updataUserMoney(Withdrawal input) {
		// return withdrawalMapper.updataUserMoney(input);
		
		if (this.selectUserMoney(input) - input.getMoney() >= 0) {

			Points points = pointsService.getPoints();
			input.setRate(Double.parseDouble(points.getPoundage()+""));
			
			int t=(int) ((input.getMoney()-points.getPoundage()) * 10 * 10);
			
			String msg = buildTlfPay(input.getBank_account_no(), input.getBank_account_name(),
					String.valueOf(t));
			logger.info("代付接口："+msg);
			
			if (msg.startsWith("[success]")) {
				return this.withdrawalMapper.updataUserMoney(input);
			}
			
			return 1;
		} else {
			return 0;
		}
	}

	@Override
	public double selectUserMoney(Withdrawal input) {
		return withdrawalMapper.selectUserMoney(input);
	}

	// TODO 此处应该要有一个返回值才对
	private String buildTlfPay(String bankCardNo, String bankCardUserName, String amount) {
		//String testTranURL = "https://113.108.182.3/aipg/ProcessServlet"; // 通联测试环境，外网（商户测试使用）
		
		String testTranURL = "https://tlt.allinpay.com/aipg/ProcessServlet"; 
		// https://tlt.allinpay.com/aipg/ProcessServlet
		//https://tlt.allinpay.com/aiap
		// String
		// tranURL="http://tlt.allinpay.com/aipg/ProcessServlet";//通联生产环境（商户上线时使用）
		boolean isfront = false;// 是否发送至前置机（由前置机进行签名）如不特别说明，商户技术不要设置为true
		String trx_code, busicode;// 100001批量代收 100002批量代付 100011单笔实时代收
									// 100014单笔实时代付
		/**
		 * 测试的时候不用修改以下业务代码，但上生产环境的时候，必须使用业务人员提供的业务代码，否则返回“未开通业务类型”
		 * 另外，特别说明：如果生产环境对接的时候返回”未开通产品“那么说明该商户开通的接口与目前测试的接口不一样，需要找业务确认
		 * 代收是批量代收接口的简称，代付 是批量代付接口的简称， 对接报文中，info下面的用户名一般是：商户号+04，
		 * 比如商户号为：200604000000445，那么对接用户一般为： 20060400000044504
		 */
		// trx_code="100001";
		// trx_code="REFUND";
		trx_code = "100014";
		// trx_code="REFUND";
		if ("100011".equals(trx_code) || "100001".equals(trx_code)) {// 收款的时候，填写收款的业务代码
			busicode = "19900";
		} else {
			busicode = "09900";
		} // 设置安全提供者,注意，这一步尤为重要
		BouncyCastleProvider provider = new BouncyCastleProvider();
		XmlTools.initProvider(provider);

		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
		Trans trans = new Trans();
		trans.setBUSINESS_CODE(busicode);
		trans.setSUBMIT_TIME(df.format(new Date()));
		trans.setACCOUNT_NAME(bankCardUserName);
		trans.setACCOUNT_NO(bankCardNo);
		trans.setACCOUNT_PROP("0");
		// trans.setACCOUNT_TYPE("01");
		trans.setAMOUNT(amount);
	
//		trans.setBANK_CODE("0308");
//		trans.setCURRENCY("CNY");
//		trans.setCUST_USERID("252523524253xx");
//		trans.setTEL("");

		return tranxService.createSingleTranx(trans, testTranURL, trx_code, busicode, isfront);
	}

}
